# -*- coding: utf-8 -*-
from django import forms
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import UserCreationForm
from django.core.context_processors import csrf
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import Context, RequestContext
from sprt import createExtInfo, get_my_dept_tree
from sprt.checkin.models import CheckinLog
from sprt.schedule.models import TodoListSchedule, Schedule
import datetime
import time

def login_site(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect("/my/overview")
            else:
                print 'y' #Return a 'disabled account' error message
        else:
            print 'x'
    else:
        c = RequestContext(request)
        c.update(csrf(request))
        createExtInfo(request,c)
        return render_to_response("accounts/login.html",c)
        #Return an 'invalid login' error message.

@login_required
def logout_site(request):
    logout(request)
    return HttpResponseRedirect("/my/login")

@login_required(login_url='/my/login')
def overview(request):
    c = RequestContext(request)
    c["checkin_tree"] = get_my_dept_tree(request.user, "/checkin/dept/", "/checkin/branch/","/checkin/user/")
    c["schedule_tree"] = get_my_dept_tree(request.user, "/schedule/dept/","/schedule/branch/","/schedule/user/")
    c["review_tree"] = get_my_dept_tree(request.user, "/review/dept/","/review/branch/","/review/user/")
    c["approve_tree"] = get_my_dept_tree(request.user, "/approved/dept/","/approved/branch/","/approved/user/")
    c["admin_tree"] = get_my_dept_tree(request.user, "/admin/dept/","/admin/dept/","/admin/user/")
    createExtInfo(request,c)
    return render_to_response("index.html",c)

@login_required(login_url='/my/login')
def home(request):
    c = RequestContext(request)
    todoList = TodoListSchedule.objects.filter(auth_user=request.user)
    if(todoList!=None):
        c["lack_schedule_cnt"] = len(list(todoList))
    reviewList = Schedule.objects.filter(created_by=request.user.id,status__gte=2)
    if reviewList != None:
        c["lack_review_cnt"] = len(list(reviewList))
    week_dict={'Monday':'星期一','Tuesday':'星期二','Wednesday':'星期三','Thursday':'星期四','Friday':'星期五','Saturday':'星期六','Sunday':'星期天'}
    c["today"] = datetime.date.today()
    c["day_of_week"] =  week_dict[time.strftime("%A",time.localtime())]
    c["week_of_year"] = time.strftime("%W",time.localtime())
    now = time.localtime(time.time())
    rows = CheckinLog.objects.extra(where=[""" user_id = %d and datediff(created_date, '%s') = 0 """ %(request.user.id, time.strftime('%Y-%m-%d',now))])
    if len(rows) > 0:
        log = rows[0]
        if log.first_login_time:
            c["first_login_time"] = log.first_login_time
        if log.last_logout_time:
            c["last_logout_time"] = log.last_logout_time
    if request.META["management_role"]:
        from django.db import connection
        cursor = connection.cursor()
        cursor.execute("select count(*) from CHECKIN_LOG C inner join auth_user A on C.user_id = A.id inner join USER_DETAIL U2 on A.id = U2.user_id inner join DEPT T on U2.dept_id = T.id where T.principal_auth_user_id = %d and (C.first_login_time is null or C.last_logout_time is null)" % request.user.id)
        c["dept_absence_cnt"] = cursor.fetchall()[0][0]
        cursor.close()
        cursor = connection.cursor()
        cursor.execute("select count(*) from SCHEDULE S inner join SCHEDULE_TYPE T on S.schedule_type_id = T.id inner join USER_DETAIL U on S.created_by_id = U.user_id inner join auth_user U2 on U.user_id = U2.id inner join DEPT D on U.dept_id = D.id left join APPROVE a on S.id = A.schedule_id where D.principal_auth_user_id = %d and S.status = 1 and (A.status =0 or A.status is null)" % request.user.id)
        c["dept_unapprove_cnt"] = cursor.fetchall()[0][0]
        cursor.close()
    createExtInfo(request,c)
    return render_to_response("accounts/home.html",c)